package org.example.websockettest.Controller;

import jakarta.servlet.http.HttpSession;
import org.example.websockettest.dao.User;
import org.example.websockettest.service.impl.RedisServiceImpl;
import org.example.websockettest.service.impl.UserServiceImpl;
import org.example.websockettest.utils.ApiResponse;
import org.example.websockettest.utils.JwtUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.util.HashMap;
import java.util.Map;

// 用户控制层
@RestController
@RequestMapping("/users")
public class UserController {
    private static final Logger logger = LoggerFactory.getLogger(UserController.class);

    @Autowired
    private UserServiceImpl userServiceImpl;
    @Autowired
    private RedisServiceImpl redisServiceImpl;
    // 注册功能
    @CrossOrigin(origins = "*", maxAge = 3600)
    @PostMapping("/register")
    public ResponseEntity<ApiResponse<User>> registerUser(@RequestParam String username, @RequestParam String password) {
        User user = userServiceImpl.register(username, password);
        if (user != null) {
            logger.info("用户注册成功: {}", username);
            return ResponseEntity.ok(ApiResponse.success("用户注册成功.", user));
        } else {
            logger.warn("用户注册失败: {}", username);
            return ResponseEntity.badRequest().body(ApiResponse.error(400, "用户注册失败."));
        }
    }

    // 登录功能
    @CrossOrigin(origins = "*", maxAge = 3600)
    @PostMapping("/login")
    public ResponseEntity<ApiResponse<Map<String, String>>> loginUser(HttpSession session, @RequestParam String username, @RequestParam String password) {
        Map<String, String> tokens = userServiceImpl.login(username, password);
        if (tokens != null) {
            return ResponseEntity.ok(ApiResponse.success("登录成功.", tokens));
        } else {
            logger.warn("用户登录失败: {}", username);
            return ResponseEntity.status(401).body(ApiResponse.error(401, "用户登录失败"));
        }
    }

    // 刷新AccessToken
    @CrossOrigin(origins = "*", maxAge = 3600)
    @PostMapping("/refreshToken")
    public ResponseEntity<ApiResponse<String>> refreshToken(@RequestHeader("Authorization") String authorization) {
        System.out.println("token刷新");
        String refreshToken = authorization.substring("Bearer ".length());
        logger.info("refreshToken" + refreshToken);
        String newAccessToken = userServiceImpl.refreshAccessToken(refreshToken);
        logger.info("newAccessToken" + newAccessToken);
        if (newAccessToken != null) {
            logger.info("Token 刷新成功");
            return ResponseEntity.ok(ApiResponse.success("Token 刷新成功.", newAccessToken));
        } else {
            logger.warn("Token 刷新失败");
            return ResponseEntity.status(401).body(ApiResponse.error(401, "Token 刷新失败"));
        }
    }

    // 验证accessToken
    @CrossOrigin(origins = "*", maxAge = 3600)
    @GetMapping("/validateToken")
    public ResponseEntity<ApiResponse<Map<String, Object>>> validateToken(@RequestHeader("Authorization") String authorization) {
        String token = authorization.substring("Bearer ".length());
        logger.info(token);
        Map<String, Object> claims = JwtUtil.parseToken(token);
        if (claims != null) {
            logger.info("Token校验成功" + claims.get("userId"));
            return ResponseEntity.ok(ApiResponse.success("Token可用.", claims));
        } else {
            logger.warn("非法Token");
            return ResponseEntity.status(401).body(ApiResponse.error(401, "Invalid or expired token."));
        }
    }

    @CrossOrigin(origins = "*", maxAge = 3600)
    @GetMapping("/details")
    public ResponseEntity<ApiResponse<Map<String, String>>> getUserDetails(@RequestHeader("Authorization") String authorization) {
        String token = authorization.substring("Bearer ".length());
        logger.info(token);
        Map<String, Object> claims = JwtUtil.parseToken(token);
        String userId = String.valueOf(claims.get("userId"));
        logger.info("userId" + userId);
        User user = userServiceImpl.findUserById(String.valueOf(userId));

        return getUserDetail(userId, user);
    }
    // 根据用户ID获取用户详情
    @CrossOrigin(origins = "*", maxAge = 3600)
    @GetMapping("/details/{userId}")
    public ResponseEntity<ApiResponse<Map<String, String>>> getUserDetailsById(@PathVariable String userId) {
        logger.info("获取用户详情，用户ID: {}", userId);
        User user = userServiceImpl.findUserById(userId);

        return getUserDetail(userId, user);
    }
//    获取用户详情封装
    private static ResponseEntity<ApiResponse<Map<String, String>>> getUserDetail(@PathVariable String userId, User user) {
        if (user!=null) {
            Map<String, String> userDetails = new HashMap<>();
            userDetails.put("id", String.valueOf(user.getUserId()));
            userDetails.put("username", user.getUsername());
            userDetails.put("email", user.getEmail());
            userDetails.put("avatar", user.getAvatar());
            userDetails.put("bio", user.getBio());
            userDetails.put("className", user.getClassName());
            userDetails.put("school", user.getSchool());
            logger.info("用户详情获取成功: {}", userDetails);
            return ResponseEntity.ok(ApiResponse.success("用户详情获取成功.", userDetails));
        } else {
            logger.warn("找不到用户: {}", userId);
            return ResponseEntity.status(404).body(ApiResponse.error(404, "找不到用户"));
        }
    }

    // 用户下线
    @CrossOrigin(origins = "*", maxAge = 3600)
    @PostMapping("/logout")
    public ResponseEntity<ApiResponse<String>> logoutUser(@RequestHeader("Authorization") String authorization) {
        logger.info("用户下线");
        // 获取id
        String token = authorization.substring("Bearer ".length());
        Map<String, Object> claims = JwtUtil.parseToken(token);
        logger.info("token" + token + "userId" + claims.get("userId"));
        String userId = String.valueOf(claims.get("userId"));
        userServiceImpl.logout(userId);
        return ResponseEntity.ok(ApiResponse.success("用户已注销成功."));
    }

    // 修改用户信息
    @CrossOrigin(origins = "*", maxAge = 3600)
    @PostMapping("/update")
    public ResponseEntity<ApiResponse<String>> updateUserInfo(@RequestParam String userId,
                                                              @RequestParam(required = false) String email,
                                                              @RequestParam(required = false) String avatar,
                                                              @RequestParam(required = false) String bio,
                                                              @RequestParam(required = false) String className,
                                                              @RequestParam(required = false) String school) {
        boolean isUpdated = userServiceImpl.updateUserInfo(userId, email, avatar, bio, className, school);

        if (isUpdated) {
            return ResponseEntity.ok(ApiResponse.success("用户信息更新成功."));
        } else {
            return ResponseEntity.status(400).body(ApiResponse.error(400, "用户信息更新失败."));
        }
    }

    // 上传头像接口
    @CrossOrigin(origins = "*", maxAge = 3600)
    @PostMapping("/uploadAvatar")
    public ResponseEntity<ApiResponse<String>> uploadAvatar(@RequestParam("file") MultipartFile file,
                                                            @RequestParam String userId) {
        String fileName = userServiceImpl.saveAvatar(file, userId);
        if (fileName != null) {
            return ResponseEntity.ok(ApiResponse.success("头像上传成功.", fileName));
        } else {
            return ResponseEntity.status(500).body(ApiResponse.error(500, "头像上传失败."));
        }
    }
    // 用户上线接口
    @CrossOrigin(origins = "*", maxAge = 3600)
    @PostMapping("/online")
    public ResponseEntity<ApiResponse<String>> userOnline(@RequestParam String username) {
        redisServiceImpl.addUser(username);
        userServiceImpl.updateUserOnlineStatus(username,true);
        return ResponseEntity.ok(ApiResponse.success("用户上线成功."));
    }

    // 用户下线接口
    @CrossOrigin(origins = "*", maxAge = 3600)
    @PostMapping("/offline")
    public ResponseEntity<ApiResponse<String>> userOffline(@RequestParam String username) {
        redisServiceImpl.removeUser(username);
        userServiceImpl.updateUserOnlineStatus(username,false);

        return ResponseEntity.ok(ApiResponse.success("用户下线成功."));
    }

    // 获取在线用户数量
    @CrossOrigin(origins = "*", maxAge = 3600)
    @GetMapping("/onlineCount")
    public ResponseEntity<ApiResponse<Long>> getOnlineUserCount() {
        long onlineUserCount = redisServiceImpl.getOnlineUserCount();
        return ResponseEntity.ok(ApiResponse.success("在线用户数量获取成功.", onlineUserCount));
    }
}
